import React, { Suspense, useTransition, useState } from "react";
import ErrorBoundary from "../components/ErrorBoundary";

interface UserProps {
  resource: any;
}
function User(props: UserProps) {
  const result = props.resource.read();
  if (result.success) {
    let user = result.data;
    return (
      <p>
        {user.id}:{user.name}
      </p>
    );
  } else {
    return <p>{result.message}</p>;
  }
}

function createResource(promise: Promise<string>) {
  let status = "pending";
  let result: any;
  return {
    read() {
      if (status === "success" || status === "error") {
        return result;
      } else {
        throw promise.then(
          (data: any) => {
            status = "success";
            result = data;
          },
          (error: any) => {
            status = "error";
            result = error;
          }
        );
      }
    },
  };
}
function fetchData(id: number): Promise<any> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ success: true, data: { id, name: "张三" + id } });
      //reject({success:false,message:'获取数据发生了错误'});
    }, 3000);
  });
}
const initialResource = createResource(fetchData(1));
export default function () {
  const [resource, setResource] = useState(initialResource);
  const [isPending, startTransition] = useTransition();
  return (
    <>
      <ErrorBoundary fallback={<h1>出错了</h1>}>
        <Suspense fallback={<h1>加载中...</h1>}>
          <User resource={resource} />
        </Suspense>
      </ErrorBoundary>
      {isPending ? " 加载中..." : null}
      <button
        disabled={isPending}
        onClick={() => {
          startTransition(() => {
            setResource(createResource(fetchData(2)));
          });
        }}
      >
        下一个用户
      </button>
    </>
  );
}
